package com.zerotwo.exam.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zerotwo.exam.common.core.result.PageResult;
import com.zerotwo.exam.common.core.result.Result;
import com.zerotwo.exam.common.core.result.ResultCode;
import com.zerotwo.exam.user.mapper.JoinClassMapper;
import com.zerotwo.exam.user.model.Classes;
import com.zerotwo.exam.user.model.JoinClass;
import com.zerotwo.exam.user.model.User;
import com.zerotwo.exam.user.model.UserAuthInfo;
import com.zerotwo.exam.user.po.CourseUserPo;
import com.zerotwo.exam.user.service.IJoinClassService;
import com.zerotwo.exam.user.service.impl.ClassesServiceImpl;
import com.zerotwo.exam.user.service.impl.JoinClassServiceImpl;
import com.zerotwo.exam.user.service.impl.UserServiceImpl;
import com.zerotwo.exam.web.annotation.Inner;
import com.zerotwo.exam.web.utils.UserAuthUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 02
 * @version 1.0
 * @Date 2024/7/5
 * @Description
 */
@Tag(name = "加入课程班级")
@RestController
@RequestMapping("/join-class")
public class JoinClassController {
    @Autowired
    JoinClassServiceImpl joinClassService;
    @Autowired
    ClassesServiceImpl classesService;
    @Autowired
    JoinClassMapper joinClassMapper;
    @Autowired
    UserServiceImpl userServiceImpl;

    @Operation(summary = "获取班级成员")
    @GetMapping("/{classId}/student/list")
    public Result getList(
            @Schema(description = "班级id") @PathVariable Integer classId,
            @RequestParam(required = false, defaultValue = "1") Long currentPage,
            @RequestParam(required = false, defaultValue = "10") Long pageSize) {
        Classes classes = classesService.getById(classId);
        Integer userId = UserAuthUtil.getUserId();
        if (classes == null) {
            return Result.failed(ResultCode.PARAM_ERROR);
        }
        if (classes.getTeacherId() != userId) {
            JoinClass isJoinClass = joinClassService.getJoinByClassId(userId, classId);
            if (isJoinClass == null) {
                return Result.msgError("未加入该课程班级");
            }
        }
        IPage<UserAuthInfo> classUsers = joinClassService.getClassUsers(classId, currentPage, pageSize);
        return Result.success(PageResult.setResult(classUsers));
    }

    @Inner
    @Operation(summary = "批量获取班级学生")
    @PostMapping("/students/list")
    public PageResult<UserAuthInfo> getBatchClassUser(
            @RequestBody @Validated CourseUserPo courseUser,
            @RequestParam(required = false, defaultValue = "true") Boolean isInlist,
            @RequestParam(defaultValue = "1") Long currPage,
            @RequestParam(required = false, defaultValue = "10") Long pageSize) {
        final IPage<UserAuthInfo> batchClassUsers = joinClassService.getBatchClassUsers(courseUser, isInlist, currPage, pageSize);
        return PageResult.setResult(batchClassUsers);
    }

    @Inner
    @Operation(summary = "获取班级人数")
    @PostMapping("/student/number")
    public Result<Long> getStudentNumberByIds(@RequestBody Set<Integer> classIds) {
        LambdaQueryWrapper<JoinClass> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(JoinClass::getClassId, classIds);
        long count = joinClassService.count(queryWrapper);
        return Result.success(count);
    }

    @Operation(summary = "新增班级学生")
    @PostMapping("/add")
    public Result addStudent(String name, @RequestBody JoinClass joinClass, String autograph) {
        try {
            // 验证用户名
            Result result = getUserName(name);
            List<User> users = (List<User>) result.getData();
            if (users.size() >= 1) {
                // 身份证号码
                Result autographResult = getUserAutograph(autograph, name);
                List<User> autographUsers = (List<User>) autographResult.getData();
                if (autographUsers.size() > 0) {
                    // 身份证重复，不可再次新增
                    return Result.failed("该身份证已存在");
                }
            } else if (users.size() < 1) {
                User user = users.get(0);
                joinClass.setStudentId(user.getId());
                joinClassService.save(joinClass);
            }
        } catch (RuntimeException e) {
            return Result.failed(e.getMessage());
        }
        return Result.success();
    }

    //验证名称
    @PostMapping("getUserName")
    public Result getUserName(String name) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (name != null) {
            qw.eq("nickname", name);
        }
        List<User> users = userServiceImpl.list(qw);
        return Result.success(users);
    }

    //验证身份证号码后四位
    @PostMapping("getUserAutograph")
    public Result getUserAutograph(String autograph, String name) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        if (autograph != null && name != null) {
            qw.like("autograph", autograph);
            qw.eq("nickname", name);
        }
        List<User> users = userServiceImpl.list(qw);
        return Result.success(users);
    }

    @Operation(summary = "删除班级学生")
    @PostMapping("delete")
    public Result deleteStudent(Integer uId, Integer cId) {
        Integer select = joinClassMapper.getJoinIds(uId, cId);
        if (select > 0) {
            joinClassService.removeById(select);
        }
        return Result.success();
    }

    @Operation(summary = "修改班级学生")
    @PostMapping("update")
    public Result updateStudent(String name, String autograph) {
        try {
            UpdateWrapper<User> uw = new UpdateWrapper<>();
            // 验证用户名
            Result result = getUserName(name);
            List<User> users = (List<User>) result.getData();
            uw.eq("nickname", name);
            if (users != null && users.size() > 1) {
                // 身份证号码
                Result autographResult = getUserAutograph(autograph, name);
                List<User> autographUsers = (List<User>) autographResult.getData();
                if (autographUsers != null && autographUsers.size() > 0) {
                    uw.eq("autograph", autograph);
                    User userToUpdate = autographUsers.get(0);
                    userServiceImpl.update(userToUpdate, uw);
                    return Result.success();
                }
            } else if (users != null && users.size() == 1) {
                userServiceImpl.update(users.get(0), uw);
                return Result.success();
            }
        } catch (RuntimeException e) {
            return Result.failed(e.getMessage());
        }
        return Result.failed();
    }
}
